import tool from "@/util/tool"
import axios from "axios"
import qs from "qs"
import router from "src/router"
import Vue from "vue"
var loading;

// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = 'http://localhost:3000/';
axios.defaults.withCredentials = true;

//POST传参序列化
axios.interceptors.request.use((config) => {
    if(config.method  === 'post'){
        config.data = qs.stringify(config.data);
    }
    return config;
},(error) =>{
    return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) =>{
    loading.close();
    return res;
}, (error) => {
    loading.close();
    return Promise.reject(error);
});

export function fetch(url, params) {
    loading = Vue.prototype.$loading({ fullscreen: true , background: 'rgba(0, 0, 0, 0.6)'});
    return new Promise((resolve, reject) => {
          axios({
            method: 'post',
            url: url,
            data: params
          })
          .then(response => {
              if(response.data.success){
                  resolve(response.data);
              }else{
                  if(response.data.msg == "未登录"){
                      router.push({path:'/login'});
                  }else{
                      reject(response.data);
                  }
              }
          })
          .catch((error) => {
              throw new Error(error);
             //reject(error)
          });
    })
}

export default {
    //登录
    login(params) {
        return fetch('/login', params)
    },
    //获取书籍列表
    booklist(params) {
        return fetch('/booklist', params)
    },
    //获取书籍详情
    bookdetail(params) {
        return fetch('/bookdetail', params)
    }
}
